<template>
	<view class="user" :class="[isDark?'dark':'', $store.state.AppStyle]" :style="{'background-color':isDark?'#1c1c1c':'#f6f6f6','min-height':isDark?'100vh':'auto'}">
		<view class="header" :style="[{height:CustomBar + 'px'}]">
			<view class="cu-bar bg-white" :style="{'height': CustomBar + 'px','padding-top':StatusBar + 'px'}">
				<view class="action" @tap="back">
					<text class="cuIcon-back"></text>
				</view>
				<view class="content text-bold" :style="[{top:StatusBar + 'px'}]">
					<block v-if="type=='add'">
						{{$t('manage.metasedit.addtagclassify')}}
					</block>
					<block v-else>
						{{$t('manage.metasedit.edittagclassify')}}
					</block>
				</view>
				<!--  #ifdef H5 || APP-PLUS -->
				<view class="action" @tap="metaEdit" v-if="type=='edit'">
					<button class="cu-btn round bg-blue">{{$t('global.save')}}</button>
				</view>
				<view class="action" @tap="metaAdd" v-if="type=='add'">
					<button class="cu-btn round bg-blue">{{$t('global.submit')}}</button>
				</view>
				<!--  #endif -->
			</view>
		</view>
		<view :style="[{padding:NavBar + 'px 10px 0px 10px'}]"></view>
		
		<form>
			<view class="cu-form-group margin-top"  v-if="type=='edit'">
				<view class="title">{{$t('manage.metasedit.classtagid')}}</view>
				<input name="input" disabled :value="mid"/>
			</view>
			<view class="cu-form-group margin-top">
				<view class="title">{{$t('global.name')}}</view>
				<input name="input" type="text" v-model="name"/>
			</view>
			<view class="cu-form-group margin-top">
				<view class="title">{{$t('global.shortname')}}</view>
				<input name="input" type="text" v-model="slug" placeholder="$t('manage.metasedit.urlencode')"/>
			</view>
			<view class="cu-form-group"  v-if="type=='add'">
				<view class="title">{{$t('global.type')}}</view>
				<view class="action">
					<text class="meta-type" :class="metaType=='category'?'act':''" @tap="metaType='category'">{{$t('global.classify')}}</text>
					<text class="meta-type" :class="metaType=='tag'?'act':''" @tap="metaType='tag'">{{$t('global.lable')}}</text>
				</view>
			</view>
			<view class="cu-form-group" v-if="metaType=='category'">
				<view class="title">{{$t('manage.metasedit.categoryparent')}}</view>
				<view class="action"  @tap="showModal" data-target="parentList">
					<text class="text-blue" v-if="curMid==0">{{$t('global.selectcategory')}}</text>
					<text class="text-blue" v-else>{{curName}}</text>
				</view>
			</view>
			<view class="cu-form-group align-start">
				<view class="title">{{$t('global.remark')}}</view>
				<textarea v-model="description" placeholder="$t('global.plsremark')"></textarea>
			</view>
			<view class="cu-form-group margin-top">
				<view class="title">{{$t('global.sort')}}</view>
				<input name="input" type="number" v-model="order" placeholder="$t('global.sorthigher')"/>
			</view>
			<view class="cu-form-group">
				<view class="title">{{$t('manage.metasedit.thumbnail')}}</view>
				<view class="action">
					<text class="cu-btn bg-blue radius" @tap="upload">{{$t('global.uploadpic')}}</text>
				</view>
			</view>
			<view class="pay-codeImg" v-if="imgurl!=''">
				<image :src="imgurl"></image>
			</view>
		</form>
		<!--  #ifdef MP -->
		<view class="post-update bg-blue" @tap="metaEdit" v-if="type=='edit'">
			<text class="cuIcon-upload"></text>
		</view>
		<view class="post-update bg-blue" @tap="metaAdd" v-if="type=='add'">
			<text class="cuIcon-upload"></text>
		</view>
		<!--  #endif -->
		<view class="cu-modal" :class="modalName=='parentList'?'show':''" @tap="hideModal">
			<view class="cu-dialog" @tap.stop="">
				<radio-group class="block" @change="midRadioChange">
					<view class="cu-list menu text-left">
						<view class="cu-item" v-for="(item,index) in parentList" :key="index">
							<label class="flex justify-between align-center flex-sub" @tap="setMid(item.mid)">
								<view class="flex-sub">{{item.name}}</view>
								<radio class="round" :class="curMid==item.mid?'checked':''" :checked="curMid==item.mid?true:false"></radio>
							</label>
						</view>
					</view>
				</radio-group>
			</view>
		</view>
	</view>
</template>

<script>
	import { localStorage } from '../../js_sdk/mp-storage/mp-storage/index.js'
	import darkModeMixin from '@/utils/darkModeMixin.js'
	export default {
		mixins: [darkModeMixin],
		data() {
			return {
				StatusBar: this.StatusBar,
				CustomBar: this.CustomBar,
				NavBar:this.StatusBar +  this.CustomBar,
				AppStyle:this.$store.state.AppStyle,
				isHuaWei: this.$API.isHuaWei(),
				isTy: false,
				mid:0,
				name:'',
				order:0,
				slug:'',
				imgurl:'',
				description:'',
				metaType:"category",
				
				type:"add",
				
				curMid:0,
				curName:"",
				parentList:[],
				modalName: null,
				//数据提交拦截，防止重复提交
				submitStatus:false,
				
			}
		},
		onPullDownRefresh(){
			
		},
		onShow(){
			var that = this;
			// #ifdef APP-PLUS
			
			//plus.navigator.setStatusBarStyle("dark")
			// #endif
			
		},
		onLoad(res) {
			var that = this;
			// #ifdef APP-PLUS || MP
			that.NavBar = that.CustomBar;
			// #endif
			if(res.type){
				that.type = res.type;
			}
			if(res.mid){
				that.mid = res.mid;
				that.geMetaInfo();
			}else{
				that.getMetaList();
			}
			
		},
		methods: {
			back(){
				uni.navigateBack({
					delta: 1
				});
			},
			midRadioChange(e){
				this.curMid = e.detail.value;
				
			},
			showModal(e) {
				this.modalName = e.currentTarget.dataset.target
			},
			hideModal(e) {
				this.modalName = null
			},
			setMid(id){
				let that = this	
				that.curMid = id;
				var list = that.parentList;
				for(var i in list){
					if(list[i].mid==that.curMid){
						that.curName = list[i].name;
					}
				}
				that.hideModal();
			},
			getMetaList(){
				var that = this;
				var data = {
					"type":"category",
					"parent":0
				}
				that.$Net.request({
					url: that.$API.getMetasList(),
					data:{
						"searchParams":JSON.stringify(that.$API.removeObjectEmptyKey(data)),
						"limit":50,
					},
					header:{
						'Content-Type':'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						if(res.data.code==1){
							var list = res.data.data;
							that.parentList = list;
							if(that.curMid!=0){
								for(var i in list){
									if(list[i].mid == that.curMid){
										that.curName = list[i].name;
									}
								}
							}
						}
						var timer = setTimeout(function() {
							that.isLoading=1;
							clearTimeout('timer')
						}, 300)
					},
					fail: function(res) {
						uni.stopPullDownRefresh()
					}
				})
			},
			geMetaInfo(){
				var that = this;
				that.$Net.request({
					url: that.$API.geMetaInfo(),
					data:{
						"key":that.mid
					},
					header:{
						'Content-Type':'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						if(res.data.code==1){
							that.name = res.data.data.name;
							that.imgurl = res.data.data.imgurl;
							that.order = res.data.data.orderKey;
							that.description = res.data.data.description;
							that.slug = res.data.data.slug;
							that.curMid = res.data.data.parent;
							that.getMetaList();
						}
					},
					fail: function(res) {
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						})
					}
				})
			},
			metaEdit() {
				var that = this;
				if(that.submitStatus){
					return false;
				}
				that.submitStatus = true;
				if (that.name == "") {
					uni.showToast({
						title: that.$t('manage.metasedit.plsname'),
						icon:'none',
						duration: 1000,
						position:'bottom',
					});
					return false
				}
				var token = "";
				if(localStorage.getItem('userinfo')){
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token=userInfo.token;
				}
				var data = {
					mid:that.mid,
					name:that.name,
					description:that.description,
					imgurl:that.imgurl,
					slug:that.slug,
					orderKey:that.order
				}
				if(that.metaType == 'category'){
					data.parent = that.curMid;
				}
				uni.showLoading({
					title: that.$t('common.loadmore')
				});
				that.$Net.request({
					
					url: that.$API.editMeta(),
					data:{
						"params":JSON.stringify(that.$API.removeObjectEmptyKey(data)),
						"token":token
					},
					header:{
						'Content-Type':'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						that.submitStatus = false;
						setTimeout(function () {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
						if(res.data.code==1){
							var timer = setTimeout(function() {
								that.back();
								clearTimeout('timer')
							}, 1000)
							
						}
					},
					fail: function(res) {
						that.submitStatus = false;
						setTimeout(function () {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						})
						uni.stopPullDownRefresh()
					}
				})
			},
			metaAdd(){
				var that = this;
				if (that.name == "") {
					uni.showToast({
						title: that.$t('manage.metasedit.plsname'),
						icon:'none',
						duration: 1000,
						position:'bottom',
					});
					return false
				}
				var token = "";
				if(localStorage.getItem('userinfo')){
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token=userInfo.token;
				}
				var data = {
					name:that.name,
					description:that.description,
					imgurl:that.imgurl,
					slug:that.slug,
					orderKey:that.order,
					type:that.metaType
				}
				if(that.metaType == 'category'){
					data.parent = that.curMid;
				}
				uni.showLoading({
					title: that.$t('common.loadmore')
				});
				that.$Net.request({
					url: that.$API.addMeta(),
					data:{
						"params":JSON.stringify(that.$API.removeObjectEmptyKey(data)),
						"token":token
					},
					header:{
						'Content-Type':'application/x-www-form-urlencoded'
					},
					method: "get",
					dataType: 'json',
					success: function(res) {
						setTimeout(function () {
							uni.hideLoading();
						}, 1000);
						if(res.data.code==1){
							uni.showToast({
								title: res.data.msg + that.$t('manage.metasedit.plscacheact'),
								icon: 'none'
							})
							var timer = setTimeout(function() {
								that.back();
								clearTimeout('timer')
							}, 1000)
						}else{
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
					},
					fail: function(res) {
						setTimeout(function () {
							uni.hideLoading();
						}, 1000);
						uni.showToast({
							title: that.$t('common.networkfail'),
							icon: 'none'
						})
						uni.stopPullDownRefresh()
					}
				})
			},
			// #ifdef APP-PLUS
			//权限检测
			showTC(){
				var that = this;
				var tc1 = false;
				let _permissionID = 'android.permission.WRITE_EXTERNAL_STORAGE';
				let _permissionID2 = 'android.permission.CAMERA';
				plus.android.checkPermission(_permissionID2,
					granted => {
						if (granted.checkResult == -1) {
							uni.showModal({
								title: that.$t('global.permissionapply'),
								content: that.$t('global.permissionapplydesc'),
								cancelText: that.$t('common.cancel'),
								confirmText: that.$t('global.agree'),
								showCancel: true,
								confirmColor: '#000',
								cancelColor: '#666',
								success: (res) => {
									if (res.confirm) {
										tc1 = true;
										that.requestPermissions();
									}else{
										that.isTy = false
										tc1 = true;
									}
								}
							})
							//还未授权当前查询的权限，打开权限申请目的自定义弹框
							that.$nextTick(() => {
								setTimeout(() => {
									that.ani = 'uni-' + that.type
								},30)
							})
						}
					},
					error => {
						console.log(error.message);
					}
				);
				plus.android.checkPermission(_permissionID,
					granted => {
						if (granted.checkResult == -1) {
							if(!tc1){
								uni.showModal({
									title: that.$t('global.permissionapply'),
									content: that.$t('global.permissionapplydesc'),
									cancelText: that.$t('common.cancel'),
									confirmText: that.$t('global.agree'),
									showCancel: true,
									confirmColor: '#000',
									cancelColor: '#666',
									success: (res) => {
										if (res.confirm) {
											return that.requestPermissions();
										}else{
											that.isTy = false
										}
									}
								})
							}
							//还未授权当前查询的权限，打开权限申请目的自定义弹框
							that.$nextTick(() => {
								setTimeout(() => {
									that.ani = 'uni-' + that.type
								},30)
							})
						}
					},
					error => {
						
					}
				);
			},
			requestPermissions() {
				let _this = this;
		
				let _permissionID = 'android.permission.WRITE_EXTERNAL_STORAGE';
				let _permissionID2 = 'android.permission.CAMERA';
				
				plus.android.checkPermission(_permissionID2,
					granted => {
						if (granted.checkResult == -1) {
							//还未授权当前查询的权限，打开权限申请目的自定义弹框
							
							_this.$nextTick(() => {
								setTimeout(() => {
									_this.ani = 'uni-' + _this.type
								},30)
							})
						}
					},
					error => {
						console.log(error.message);
					}
				);
				plus.android.requestPermissions([_permissionID2],
					(e) => {
					//关闭权限申请目的自定义弹框
					_this.ani = '';
					_this.$nextTick(() => {
						
					})
					if (e.granted.length > 0) {
						//当前查询权限已授权
						plus.android.checkPermission(_permissionID,
							granted => {
								if (granted.checkResult == -1) {
									//还未授权当前查询的权限，打开权限申请目的自定义弹框
									_this.$nextTick(() => {
										setTimeout(() => {
											_this.ani = 'uni-' + _this.type
										},30)
									})
								}
							},
							error => {
								
							}
						);
						plus.android.requestPermissions([_permissionID],
							(e) => {
							//关闭权限申请目的自定义弹框
							_this.ani = '';
							_this.$nextTick(() => {
								
							})
							if (e.granted.length > 0) {
								//当前查询权限已授权
								_this.isTy = true
							}
							if (e.deniedAlways.length > 0) {
								//当前查询权限已被永久禁用，此时需要引导用户跳转手机系统设置去开启
								uni.showModal({
									title: that.$t('global.fogettips'),
									content: that.$t('global.noalbumpermiss'),
									cancelText: that.$t('common.cancel'),
									confirmText: that.$t('global.setitup'),
									showCancel: true,
									confirmColor: '#000',
									cancelColor: '#666',
									success: (res) => {
										if (res.confirm) {
											_this.goSetting();
										}else{
											_this.isTy = false
										}
									}
								})
							}
						})
					}
					if (e.deniedAlways.length > 0) {
						//当前查询权限已被永久禁用，此时需要引导用户跳转手机系统设置去开启
						uni.showModal({
							title: that.$t('global.fogettips'),
							content: that.$t('global.nocamerapermiss'),
							cancelText: that.$t('common.cancel'),
							confirmText: that.$t('global.setitup'),
							showCancel: true,
							confirmColor: '#000',
							cancelColor: '#666',
							success: (res) => {
								if (res.confirm) {
									_this.goSetting();
								}else{
									_this.isTy = false
								}
							}
						})
					}
				})
			},
			//跳转手机系统设置
			goSetting() {
				var Intent = plus.android.importClass("android.content.Intent");
				var Settings = plus.android.importClass("android.provider.Settings");
				var Uri = plus.android.importClass("android.net.Uri");
				var mainActivity = plus.android.runtimeMainActivity();
				var intent = new Intent();
				intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
				var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
				intent.setData(uri);
				mainActivity.startActivity(intent);
			},
			// #endif
			upload(){
				let that = this;
				if(that.isTy==false&&that.isHuaWei==1){
					that.showTC()
				}
				var token = "";
				if(localStorage.getItem('userinfo')){
					var userInfo = JSON.parse(localStorage.getItem('userinfo'));
					token=userInfo.token;
				}
				uni.chooseImage({
					count: 1,  // 最多可以选择的图片张数，默认9
					sourceType: ['album', 'camera'], 
				    success: function (res) {						
						uni.showLoading({
							title: that.$t('common.loadmore')
						});
						const tempFilePaths = res.tempFilePaths;
						for(let i = 0;i < tempFilePaths.length; i++) {
							const uploadTask = uni.uploadFile({
							  url : that.$API.upload(),
							  filePath: tempFilePaths[i],
							  name: 'file',
							  formData: {
							   'token': token
							  },
							  success: function (uploadFileRes) {
								  if(i==tempFilePaths.length-1){
									  setTimeout(function () {
									  	uni.hideLoading();
									  }, 1000);
								  }
								  
								var data = JSON.parse(uploadFileRes.data);
								//var data = uploadFileRes.data;
								uni.showToast({
									title: data.msg,
									icon: 'none'
								})
								if(data.code==1){
									   //插入文章
									that.imgurl = data.data.url;
								}
								},fail:function(){
									setTimeout(function () {
										uni.hideLoading();
									}, 1000);
								}
							});
						}
					}
				})
			},
		}
	}
</script>